import { Effect, Reducer } from 'umi';
import { create, queryAllProject, queryAllPorta, postPorta } from '@/services/information';
import {  AllProjectList, PortaItem } from '../type'

export interface RoleModelState {
  allProjectList: Array<AllProjectList>;
  portaList: Array<PortaItem>;
  projectParentList: Array<AllProjectList>;
}

export interface ProjectsModelType {
  namespace: 'role';
  state: RoleModelState;
  effects: {
    create: Effect;
    fetchAllProject: Effect;
    fetchAllPorta: Effect;
    submitPorta: Effect;
  };
  reducers: {
    save: Reducer;
  };
}

const RoleModel: ProjectsModelType = {
  namespace: 'role',

  state: {
    allProjectList: [], // 项目列表
    projectParentList: [], // 项目列表 项目一大类数据
    portaList: [], // 看板列表
  },

  effects: {
    // 创建角色
    *create({ payload, callback }, { call }) {
      const response = yield call(create, payload);

      if (callback) callback(response);
    },

    // 获取所有项目列表
    *fetchAllProject(_, { call, put }) {
      const response = yield call(queryAllProject);

      let treeData: Array<any> = [];
      const { payload } = response;
      if (payload) {
        // 获取树形结构父级
        payload.map((item: any) => {
          if (JSON.stringify(treeData).indexOf(JSON.stringify(item.project)) === -1) {
            treeData.push(item.project);
          }
        });
      }
      yield put({
        type: 'save',
        payload: { allProjectList: response.payload } ,
      });

      yield put({
        type: 'save',
        payload: { projectParentList: treeData },
      });
    },

    // 获取所有看板列表
    *fetchAllPorta(_, { call, put }) {
      const response = yield call(queryAllPorta);
      yield put({
        type: 'save',
        payload: { portaList: response.payload },
      });
    },

    // 保存看板权限
    *submitPorta({ payload, callback }, { call }) {
      const response = yield call(postPorta, payload);

      if (callback) callback(response);
    },
  },

  reducers: {
    save (state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
  },
};

export default RoleModel;
